package wgff.xml.iTunes
{
	import flash.events.*;
	import flash.utils.Dictionary;
	
	import mx.collections.ArrayCollection;
	
	import wgff.xml.globalXml;
	
	public class libraryParser extends EventDispatcher
	{
		public function libraryParser()
		{
		}

		private static var lib:XML;
		
		private var xml:XML;
		private var loader:globalXml;
		
		public var itemsTotal:Number = 0;
		public var itemsLoaded:Number = 0;
		public var bytesLoaded:Number = 0;
		public var bytesTotal:Number = 0;
		public var percentProcessed:Number = 0;
		public var percentLoaded:Number = 0;
		public var percentTotal:Number = 0;
		public var data:ArrayCollection;
		
		public function parseXml(xml:XML):ArrayCollection {
			var ac:ArrayCollection = new ArrayCollection();
			lib = xml;
			this.itemsTotal = 500;
			var i:Number = 0;
			
			for each(var d:XML in xml.dict.dict.dict) {
				i++;
				ac.addItem(parseSong(d));
				this.itemsLoaded = i;
				this.percentProcessed = Math.round((this.itemsTotal * 100) / i);
				this.percentTotal = 50 + Math.round(this.percentProcessed / 2);
				dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS));
			}
			return ac;
		}
		
		public function parseXmlFromUrl(url:String):void {
			this.data = new ArrayCollection();
			this.loader = new globalXml();
			this.loader.addEventListener(Event.COMPLETE, getXML);
			//this.loader.addEventListener(ProgressEvent.PROGRESS, progressXML);
			this.loader.sendXML(url);
		}
		
		public function getXML(e:Event):void {
			this.xml = e.target.xml as XML;
			this.data = this.parseXml(this.xml);
			dispatchEvent(new Event(Event.COMPLETE));
		}
		
		private function progressXML(event:ProgressEvent):void
        {
            this.bytesLoaded = this.loader.bytesLoaded;
            this.bytesTotal = this.loader.bytesTotal;
            this.percentLoaded = Math.round((this.loader.bytesTotal * 100) / this.loader.bytesLoaded);
            this.percentTotal = Math.round(this.percentLoaded / 2);
            dispatchEvent(new ProgressEvent(ProgressEvent.PROGRESS));
        }
		
		private function parseSong(song:XML):playListEntry {
			var ple:playListEntry = new playListEntry();
			var tune:Dictionary= new Dictionary();
			
			var key:String;
			for each (var tuneProperty:XML in song.children()) {
				if (tuneProperty.name() == "key") key = tuneProperty.text();
				else tune[key] = String(tuneProperty.text());
			}
			ple.album = tune.Album;
			ple.artist = tune.Artist;
			ple.bitRate = tune["Bit Rate"];
			ple.genre=tune.Genre;
			ple.location=tune.Location;
			ple.name = tune.Name;
			ple.sampleRate = tune["Sample Rate"];
			ple.songLength = tune["Total Time"];
			ple.year=tune.Year;
			ple.lengthString = ple.songLength.toString();
			return ple;
		}
	}
}
 
 
